package com.dtborad.myblog.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dtborad.myblog.entity.Categories;
import com.dtborad.myblog.entity.Users;
import com.dtborad.myblog.mapper.UsersMapper;
import com.dtborad.myblog.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UsersMapper, Users> implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public Integer registerUser(Users user) {
        //Users newUser = new Users();
        int insert = 0;
        try {
            //首先校验用户是否已存在
            LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Users::getUsername, user.getUsername());
            Users originUser = usersMapper.selectOne(wrapper);
            if (originUser == null) {
                user.setStatus(0);
                insert = usersMapper.insert(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return insert;
    }

    @Override
    public Page<Users> getAllUserByPageSize(int pagenum, int pagesize, String username, String nickname) {
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotBlank(username) && StrUtil.isNotBlank(nickname)){
            wrapper = wrapper.like(Users::getUsername, username).like(Users::getNickname, nickname);
        }else if(StrUtil.isNotBlank(username) || StrUtil.isNotBlank(nickname)){
            if(StrUtil.isNotBlank(username)){
                wrapper = wrapper.like(Users::getUsername, username);
            }
            if(StrUtil.isNotBlank(nickname)){
                wrapper = wrapper.like(Users::getNickname, nickname);
            }
        }else{
            //两者均为空, 查询全部数据
            return usersMapper.selectPage(new Page<>(pagenum, pagesize), null);
        }
        return usersMapper.selectPage(new Page<>(pagenum, pagesize), wrapper);
    }
}
